package com.tinem.platform.web.auth.login.oauth2.ext;

import com.tinem.platform.module.pojo.co.SessionKeyEnum;
import com.tinem.platform.web.auth.login.code.CodeAuthenticationFilter;
import com.tinem.platform.web.auth.login.code.CodeAuthenticationProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class OAuth2AuthenticationSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {

    @Autowired
    OAuth2AuthenticationProvider oAuth2AuthenticationProvider;

    @Autowired
    Map<String,AuthenticationSuccessHandler> authenticationSuccessHandlerMap;

    @Override
    public void configure(HttpSecurity http) throws Exception {

        OAuth2AuthenticationFilter oAuth2AuthenticationFilter = new OAuth2AuthenticationFilter();
        oAuth2AuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        oAuth2AuthenticationFilter.setAuthenticationSuccessHandler((request,response,authentication)->{
            String name = "authenticationSuccessHandler-"+request.getSession().getAttribute(SessionKeyEnum.oauth2_type.getKey());
            authenticationSuccessHandlerMap.get(name).onAuthenticationSuccess(request,response,authentication);
        });
        // 将短信验证码校验器注册到 HttpSecurity， 并将短信验证码过滤器添加在 UsernamePasswordAuthenticationFilter 之前
        http
                .authenticationProvider(oAuth2AuthenticationProvider)
                .addFilterAfter(oAuth2AuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
        ;

    }
}